package com.huanzhidadi.single.daemon;

import java.util.concurrent.TimeUnit;

/**
 * 守护线程在主方法结束时候结束
 */
public class DaemonTest {
    public static void main(String[] args) {

        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    System.out.println(Thread.currentThread().getName() + "----睡眠一秒-----");
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        //默认为false,设置为false代表非守护线程,true为守护线程
        thread.setDaemon(true);

        // 用户线程
        Thread parentThread = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "----用户线程开始-----");
            thread.start();
        });
        parentThread.start();
        // 加点延迟，让线程能启动起来
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        parentThread.interrupt();
        if (!parentThread.isAlive()) {
            System.out.println(Thread.currentThread().getName() + "----用户线程结束-----");
        }
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "主线程结束，守护线程也会结束。");

    }
}
